package com.xlh.listener;

import cn.hutool.core.date.DateUtil;
import com.xlh.constant.CourseTestConstant;
import com.xlh.service.courseTest.PaperAnswerSheetService;
import com.xlh.service.courseTest.PaperService;
import com.xlh.util.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author zhr 2019/2/22
 */
public class EndCourseTestTask implements DelayedTask {

    private static final Logger logger = LoggerFactory.getLogger(EndCourseTestTask.class);

    private static PaperService paperService = SpringContextUtil.getBean(PaperService.class);
    private static PaperAnswerSheetService answerSheetService = SpringContextUtil.getBean(PaperAnswerSheetService.class);

    // 试卷id
    private Long paperId;
    // 过期时间,单位:毫秒
    private Long expireTime;

    public EndCourseTestTask(Long paperId, Date endTime) {
        this.paperId = paperId;
        this.expireTime = endTime.getTime();
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(expireTime - DateUtil.current(false), TimeUnit.MILLISECONDS);
    }

    @Override
    public void run() {
        try {
            // 执行强制交卷,并将试卷状态变更为'考试结束'
            paperService.endPaper(this.paperId);

            // 延迟一分钟进行试卷批阅
            Thread.sleep(CourseTestConstant.AUTO_CHECK_DELAY);

            // 将学生的答题情况提交并修改考试状态为'已交卷'
            answerSheetService.endTest(this.paperId);
        } catch (Exception e) {
            logger.error("自动交卷错误", e);
        }
    }

    @Override
    public int compareTo(Delayed o) {
        if (o == this) {
            return 0;
        }
        if (o instanceof EndCourseTestTask) {
            EndCourseTestTask other = (EndCourseTestTask) o;
            if (expireTime < other.expireTime) {
                return -1;
            } else if (expireTime > other.expireTime) {
                return 1;
            }
        }
        return 0;
    }

}
